import Mn from 'backbone.marionette';
import { closeModal } from 'tools.js';


const ModalBehavior = Mn.Behavior.extend({
    /** Modal behaviour for views occuring within a modal
     *
     * Views adopting this behavior MUST
     *  - define an `id` attribute.
     *  - contain a <div class="modal_content_layout"> element (the modal body)
     *
     * fires following events

        modal:beforeClose
        modal:afterNotifySuccess
        destroy:modal

     */
    modalClasses: 'modal_view modal_form appear',
    ui: {
        close: '.close',
        modal: '>:first-child',
        modalbody: '>:first-child .modal_content_layout',
    },
    events: {
        'click @ui.close': 'onClose',
    },
    onAttach(){
        console.log("ModalBehavior : Showing the modal");
        this.ui.modal.addClass(this.modalClasses);
        this.ui.modal.css('display', 'flex');
        document.body.classList.add('modal_open');
        this.ui.close.focus();
    },
    onClose(){
        this.view.trigger("modal:canceled");
        console.log("Trigger modal:beforeClose from ModalBehavior");
        this.view.triggerMethod('modal:beforeClose');
        console.log("Trigger modal:close from ModalBehavior");
        this.view.triggerMethod('modal:close');
    },
    onModalClose() {
        console.log("ModalBehavior.onModalClose");
        closeModal(this.ui.modal);
        this.triggerFinish();
        document.body.classList.remove('modal_open');
    },
    triggerFinish() {
        console.log("Trigger destroy:modal from ModalBehavior");
        this.view.triggerMethod('destroy:modal');
        this.view.destroy();
    },
    onModalNotifySuccess() {
        var modalbody = this.getUI('modalbody');
        let view = this.view;
        if (modalbody.length === 0) {
            console.error(
                "No modalbody found, ModalBehavior is not implemented correctly by view/template.",
                view,
                "Consider adding a matching element or overriding ui.modalbody in view."
            );
        }
        modalbody.effect(
            'highlight',
            {color: 'rgba(0,0,0,0)'},
            800,
            view.triggerMethod.bind(view, 'modal:after:notifySuccess')
        );
        modalbody.addClass('action_feedback success');
    },
});
export default ModalBehavior;
